package com.ynny.usermanager.dao;

import com.ynny.usermanager.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public User selectUserById(Integer id) {
        String sql = "select * from user where id = ?";
        User user = jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(User.class),
                id);

        return user;
    }

    @Override
    public List<User> selectAllUsers() {
        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(User.class));
        return users;
    }

    @Override
    public int addUser(User user) {
        String sql = "insert into user(name,password,age) values(?,?,?)";
        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge());
        return i;
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set name = ?,password = ?,age = ? where id = ?";
        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge(),
                user.getId());
        return i;
    }

    @Override
    public int deleteUser(Integer id) {
        String sql = "delete from user where id = ?";
        int i = jdbcTemplate.update(sql,id);
        return i;
    }

    @Override
    public User selectUserByUserName(String username) {
        String sql = "select * from user where name = ?";
        User user = jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(User.class),
                username);
        return user;
    }
}